package com.zxw.文件.视频;

import cn.hutool.core.date.DateUtil;
import org.bytedeco.ffmpeg.avformat.AVFormatContext;
import org.bytedeco.javacv.*;

import java.io.File;
import java.util.Date;

public class JavaCVTest {
    public static void main(String[] args) throws Exception {
        String input1 = "C:\\Users\\Administrator\\Pictures\\Camera Roll\\视频\\考试测试2min视频.mp4";
        String input2 = "C:\\Users\\Administrator\\Pictures\\Camera Roll\\视频\\考试测试3秒钟视频.MP4";
        String longV = "C:\\Users\\Administrator\\Pictures\\Camera Roll\\视频\\132m.mp4";

        String pinjiePath = "D:\\load\\视频\\拼接\\";
        String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".mp4";
        String output = pinjiePath + fileName;

        // 获取视频时间demo start
        File file = new File(input2);
        FFmpegFrameGrabber grabberTime = new FFmpegFrameGrabber(file);
        grabberTime.start();
        AVFormatContext formatContext = grabberTime.getFormatContext();
        long duration = formatContext.duration(); // 视频时长，以微秒为单位
        grabberTime.stop();
        grabberTime.release();
        long durationInSeconds = duration / 1000000; // 转换为秒
        System.out.println("视频时长: " + durationInSeconds + " 秒");
        // 获取视频时间demo end

        // 拼接视频demo start
        FrameGrabber grabber1 = new FFmpegFrameGrabber(input1);
        FrameGrabber grabber2 = new FFmpegFrameGrabber(input2);

        try {
            grabber1.start();
            grabber2.start();

            FrameRecorder recorder = new FFmpegFrameRecorder(output, grabber1.getImageWidth(), grabber1.getImageHeight());
            recorder.setFormat("mp4");
            recorder.start();

            Frame frame;

            while ((frame = grabber1.grabFrame()) != null) {
                recorder.record(frame);
            }

            while ((frame = grabber2.grabFrame()) != null) {
                recorder.record(frame);
            }

            grabber1.stop();
            grabber2.stop();
            recorder.stop();

            System.out.println("视频拼接完成。");

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 拼接视频demo end

    }
}
